package com.atXiao.video.utils;

import com.alibaba.fastjson.JSONArray;
import com.atXiao.video.common.BaseResponse;
import com.atXiao.video.common.ResultUtils;
import com.atXiao.video.dto.ChatModel;
import com.atXiao.video.websocket.WebSocket;
import com.google.gson.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;

@Component
public class ChatGptUntil {

//    @Value("${openai.token}")
    private String ApiKey = "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";
//    @Value("${proxy.host}")
    private String host = "localhost";
//    @Value("${proxy.port}")
    private int port = 63649;

    /**
     * 获取chatgpt的答案
     */
    @Async
    public String getRespost(Long conversionid, List<ChatModel> messagelist) throws IOException {
//        建立连接
        String url = "https://api.openai.com/v1/chat/completions";
        HashMap<String, Object> bodymap = new HashMap<>();

        bodymap.put("model", "gpt-3.5-turbo");
        bodymap.put("temperature", 0.7);
        bodymap.put("messages", messagelist);
        bodymap.put("stream", true);
        bodymap.put("max_tokens", 1000);
        Gson gson = new Gson();
        String s = gson.toJson(bodymap);
        URL url1 = new URL(url);
        HttpURLConnection conn = (HttpURLConnection) url1.openConnection(new Proxy(Proxy.Type.HTTP, new InetSocketAddress(host, port)));
        conn.setRequestMethod("POST");
        conn.setRequestProperty("Authorization", "Bearer " + ApiKey);
        conn.setRequestProperty("Content-Type", "application/json");
        conn.setRequestProperty("stream", "true");
        conn.setDoOutput(true);
        //    写入请求参数
        OutputStream os = conn.getOutputStream();
        BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(os, Charset.forName("UTF-8")));
        writer.write(s);
        writer.close();
        os.close();

        InputStream inputStream = conn.getInputStream();

        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        String line = null;
        StringBuffer answoer = new StringBuffer();
        while ((line = bufferedReader.readLine()) != null) {

            line = line.replace("data:", "");
            JsonElement jsonElement = JsonParser.parseString(line);
            if (!jsonElement.isJsonObject()) {

                continue;
            }
            JsonObject asJsonObject = jsonElement.getAsJsonObject();
            JsonArray choices = asJsonObject.get("choices").getAsJsonArray();
            if (choices.size() > 0) {
                JsonObject choice = choices.get(0).getAsJsonObject();
                JsonObject delta = choice.get("delta").getAsJsonObject();
                if (delta != null) {
                    if (delta.has("content")) {
//                        发送消息
                        String content = delta.get("content").getAsString();
                        BaseResponse<String> success = ResultUtils.success(content);
                        WebSocket webSocket = new WebSocket();

                        webSocket.sendMessageByUserId(conversionid, gson.toJson(success));
                        answoer.append(content);
//                      打印在控制台中
                        System.out.print(content);
                    }
                }
            }

        }
        String context = answoer.toString();
        System.out.println("组装好的消息:"+context);
        return context;
    }


    public static void main(String[] args) {
        JSONArray newCollectRowKeys = new JSONArray();
        newCollectRowKeys.add("111");
        System.out.println(newCollectRowKeys);

    }



}
